package com.nci.cloud.unit.management.MessagePivotServer;
import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.io.UnsupportedEncodingException;

public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1)

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)

    /*    ByteBuf in = (ByteBuf) msg;
        ctx.write(msg); // (1)
        ctx.flush(); // (2)*/

         ByteBuf in = (ByteBuf) msg;
         byte[] line = new byte[in.readableBytes()];
         in.readBytes(line);

        try {
            System.out.println(new String(line,"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ByteBuf out = Unpooled.copiedBuffer("receive".getBytes());
        ctx.writeAndFlush(out); // (1)


      /*  try {

            System.out.print(in.toString(CharsetUtil.UTF_8));
            ByteBuf buf = Unpooled.buffer(16);
            buf.getBytes(0,"Received".getBytes());
            ctx.write(buf); // (1)
            ctx.flush(); // (2)
            System.out.println("echo");
        } finally {
            ReferenceCountUtil.release(msg); // (2)
        }*/
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}